package utils;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Created by asus on 2017/5/14.
 */
public class JDBCUtils {
    private static DataSource dataSource=null;


    public static Connection getConnection(){
        InputStream in=JDBCUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");
        Properties pro=new Properties();
        Connection connection=null;
        try{
            pro.load(in);
            dataSource= BasicDataSourceFactory.createDataSource(pro);
        }catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try{
            connection=dataSource.getConnection();
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void release(ResultSet resultSet, Statement statement,Connection connection){
        try{
            if(resultSet!=null)
                resultSet.close();
        }catch (SQLException e){
            System.out.println("resultset close wrong");
        }
        try{
            if(statement!=null)
                statement.close();
        }catch (SQLException e){
            System.out.println("statement close wrong");
        }
        try{
            if(connection!=null)
                connection.close();
        }catch (SQLException e){
            System.out.println("connection close wrong");
        }
    }
}
